<template>
    <div class="content">
        <div class="search-bar">
            <el-form label-width="90px" style="width: 100%">
                <div class="flex">
                    <div class="flex9">
                        <el-form-item label="产品代码/名称:">
                            <el-select v-model="searchParams.fundProductCodes" filterable multiple collapse-tags clearable size="mini">
                                <el-option
                                    v-for="i in computedFundStorage"
                                    :key="i.fundCode"
                                    :label="i.fundProductCode + ' ' + i.fundName"
                                    :value="i.fundCode"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div class="flex9" style="min-width: 150px">
                        <el-form-item label="连续超限天数:">
                            <span style="width: 20px; display: inline-block">≥</span>
                            <el-input
                                style="width: 65%"
                                v-model="searchParams.prohibitionDate"
                                size="mini"
                                type="number"
                                class="item"
                                clearable
                            ></el-input>
                        </el-form-item>
                    </div>
                    <div class="flex9">
                        <!--  v-if="type == 'today'" #28976 【招商资管-风险处置中心-历史指标报告】查询条件与需求不一致，少了按条目名称查询 -->
                        <el-form-item label="系统配置条目:">
                            <el-input style="width: 100%" v-model="searchParams.entryName" size="mini" class="item" clearable></el-input>
                        </el-form-item>
                    </div>
                    <div class="flex9">
                        <el-form-item label="指标状态:">
                            <el-select v-model="searchParams.triggerTypes" filterable multiple collapse-tags clearable size="mini">
                                <el-option v-for="(value, key) in thresholdTypePojo" :key="key" :label="value" :value="key"> </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div class="flex8">
                        <el-form-item label="是否展示最新:" v-if="type == 'history'">
                            <el-select v-model="searchParams.isNew" size="mini">
                                <el-option label="是" value="0"></el-option>
                                <el-option label="否" value="1"></el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div class="flex11" v-if="type == 'history'">
                        <el-form-item label="计算日期:" label-width="80px">
                            <el-date-picker
                                v-model="searchParams.calDate"
                                type="date"
                                placeholder="选择日期"
                                value-format="yyyyMMdd"
                                format="yyyy-MM-dd"
                                size="mini"
                                style="width: 100%"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </div>
                    <div class="flex13" style="min-width: 335px">
                        <el-button size="mini" type="primary" @click="handleBtn('search')">查询</el-button>
                        <el-button size="mini" @click="handleBtn('export')">导出</el-button>
                        <el-button size="mini" @click="handleBtn('layout')">布局设置</el-button>
                        <el-button size="mini" @click="handleBtn('refresh')">刷新</el-button>
                    </div>
                </div>
            </el-form>
        </div>
        <RiskTableP
            ref="risk-table"
            :tableConfig="tableConfig"
            :tableData="tableData"
            :column="showColumns"
            :paging="paging"
            v-loading="tableLoading"
            @page-change="getTableData"
            :key="tableKey"
            style="height: calc(100% - 75px)"
            :cell-style="cellStyle"
        >
            <template #prohibitionDate="{ row }">
                <el-tag size="mini" :class="handleTagStyle(row.prohibitionDate)" v-if="row.prohibitionDate !== undefined">{{
                    row.prohibitionDate
                }}</el-tag>
                <span v-else> -- </span>
            </template>
            <template #insideDays="{ row }">
                <el-tag style="background-color: #02a7f0; color: #fff; width: 35px;text-align:center" size="mini">{{ row.insideDays || 0 }}</el-tag>
            </template>

            <template #operation="{ row }">
                <a href="javascript:;" @click="handleBtnLook(row)">查看</a>
                <!-- <RiskIconButton type="primary" icon="el-icon-view" topTitle="查看" @on-click="handleBtnLook(row)"></RiskIconButton> -->
            </template>
        </RiskTableP>

        <!-- 布局设置 -->
        <RiskTableLayout
            ref="risk-table-layout"
            :tableName="type === 'today' ? 'INDEX_REPORT' : 'INDEX_REPORT_HIS'"
            :visible.sync="layoutDialog"
            :column="columns"
            :fixedColumns="fixedColumns"
            :resetNoSelectedFieldList="resetNoSelectedFieldList"
        />

        <!-- 静态报告详情 -->
        <StaticDetail v-if="staticVisible" :visible.sync="staticVisible" :resultId="resultId" :history="history" />
    </div>
</template>
<script lang="ts">
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { ColumnVO, PageVO, TableConfigVO, VueObject } from '@/common/vo';
import { downLoadFile } from '@/utils/request';
import RiskPagination from '@/common/components/risk-pagination.vue';
import { changeOptions, dateFormat, numberFormat, timeFormat } from '@/utils/tools';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import API from '../api/index-report';
import { IndexReportDTO, IndexReportRepVO, IndexReportVO } from '../vo/index-report';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import RiskTableLayout from '@/common/components/risk-table-layout-plus.vue';
import XEUtils from 'xe-utils';
import moment from 'moment';
import StaticDetail from '../../components/static-detail.vue';
@Component({ name: 'IndexReportList', components: { RiskTableP, RiskEntryInput, RiskTableLayout, RiskPagination, RiskIconButton, StaticDetail } })
export default class IndexReportList extends Vue {
    @Prop({ default: 'today' }) type: string;

    dateFormat = dateFormat;

    searchParams: IndexReportDTO = {
        fundProductCodes: [],
        unit: '',
        prohibitionDate: '', // 超限天数
        prohibitionDateUnit: '2', // 超限天数单位 (固定为大于等于，等后端修改，该查询字段可移除)
        entryName: '',
        triggerTypes: [],
        calDate: moment(new Date())
            .subtract(1, 'days')
            .format('YYYYMMDD'),
        isNew: '0',
    };
    paging: PageVO = { currentPage: 1, pageSize: 25, total: 0 };
    tableLoading: boolean = false;
    tableConfig: TableConfigVO = {
        rowKey: 'resultId', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    tableData: IndexReportVO[] = [];
    columns: any[] = [
        {
            type: 'checkbox',
            selectedAll: false,
            fixed: 'left',
            align: 'center',
            width: 60,
        },
        {
            title: '产品代码/名称',
            field: 'dictFundCodes',
            fixed: 'left',
            minWidth: 150,
            render: value => this.formatDictFundCodes(value),
        },
        {
            title: '条款来源',
            field: 'articeInfo',
            minWidth: 200,
        },
        {
            title: '条款原文',
            field: 'clauseCode',
            minWidth: 200,
        },
        {
            title: '条目编号',
            field: 'entryCode',
            minWidth: 100,
        },
        {
            title: '系统配置条目',
            field: 'entryName',
            minWidth: 200,
        },
        {
            title: '计算日期',
            field: 'calDate',
            minWidth: 140,
            render: (value, row) => dateFormat(value) + ' ' + timeFormat(row.calTime) || '--',
        },
        {
            title: '估值日期',
            field: 'tradeDate',
            minWidth: 100,
            render: value => dateFormat(value) || '--',
        },
        {
            title: '控制阈值',
            field: 'thresholdValue',
            minWidth: 120,
            render: (value, row) => (value != undefined ? this.compareTextPojo[row.compareType] + numberFormat(value, 2) : '--'),
        },
        {
            title: '计算值',
            field: 'result',
            minWidth: 120,
            render: value => (value != undefined ? numberFormat(value, 2) : '--'),
        },
        {
            title: '首次超限日期',
            field: 'firstDate',
            minWidth: 120,
            render: value => dateFormat(value) || '--',
        },
        {
            title: '连续超限天数',
            field: 'prohibitionDate',
            minWidth: 120,
        },
        {
            title: '超限调整天数',
            field: 'insideDays',
            minWidth: 120,
        },
        {
            title: '反馈情况',
            field: 'feedbackStatus',
            minWidth: 100,
            render: value => this.feedbackStatusPojo[value] || '--',
        },
        {
            title: '超限事件分布',
            field: 'adjustProgerss',
            minWidth: 120,
            render: (value, record) => record.adjustProgerssName?.join(',') || '--',
        },
        {
            title: '超限原因概述',
            field: 'overrunInfo',
            minWidth: 200,
        },
        {
            title: '超出阈值',
            field: 'exceedThreshold',
            minWidth: 100,
            render: value => (value != undefined ? numberFormat(value, 2) : '--'),
        },
        {
            title: '指标状态',
            field: 'triggerType',
            minWidth: 100,
            render: value => this.thresholdTypePojo[value] || '--',
        },
        { title: '操作', field: 'operation', minWidth: 100, align: 'center', fixed: 'right' },
    ];
    resetNoSelectedFieldList: ColumnVO[] = [
        {
            title: '条目编号',
            field: 'entryCode',
            minWidth: 100,
        },
        {
            title: '系统配置条目',
            field: 'entryName',
            minWidth: 200,
        },
        {
            title: '首次超限日期',
            field: 'firstDate',
            minWidth: 120,
            render: value => dateFormat(value) || '--',
        },
        {
            title: '反馈情况',
            field: 'feedbackStatus',

            minWidth: 100,
            render: value => this.feedbackStatusPojo[value] || '--',
        },
    ];
    showColumns: ColumnVO[] = [];
    fixedColumns: ColumnVO[] = [
        { title: '产品代码/名称', field: 'dictFundCodes' },
        { title: '操作', field: 'operation' },
    ];
    comparePojo: any = {
        '4': '=',
        '0': '>',
        '1': '<',
        '2': '≥',
        '3': '≤',
    };

    // 比较方向
    // compareTextPojo: any = DictionConstUtil.CompareDirection;
    compareTextPojo: any = {
        '0': '>',
        '1': '<',
        '2': '≥',
        '3': '≤',
        '4': '=',
        '5': '≠',
        '6': ' ',
    };

    // 指标状态
    thresholdTypePojo: any = DictionConstUtil.ThresholdType;

    // 反馈情况
    feedbackStatusPojo = {
        '0': '待反馈',
        '1': '已反馈',
    };
    // 超限事件分布
    adjustProgresssPojo = {
        '1': '超3天未反馈',
        '2': '80%调整期',
        '3': '距调整期前2日',
        '4': '其他调整期内',
        '5': '未及时调整',
    };

    layoutDialog: boolean = false;

    fundStorage: any[] = [];
    tableKey: number = 0;

    resultId: any = '';
    history: any = '';
    staticVisible: boolean = false;
    // 已选项前置
    get computedFundStorage() {
        let arr = changeOptions(this.searchParams.fundProductCodes, this.fundStorage, 'fundCode');
        return arr;
    }

    async mounted() {
        // 监听布局设置

        this.$watch(
            () => {
                return (this.$refs['risk-table-layout'] as VueObject).showColumns;
            },
            val => {
                this.showColumns = val && val.length ? val : this.columns;
                this.tableKey++;
            }
        );

        this.getTableData();
        this.fundStorage = await SGU_CACHE('FundInfoByUser', '/fundInfo/list/byUser/like', []);
    }

    /**
     * 表格数据
     */
    getTableData(): void {
        if (this.type == 'history' && !this.searchParams.calDate) {
            this.yh_message_error('计算日期不可为空');
            return;
        }
        this.tableLoading = true;
        API.getIndexReportList({ ...this.searchParams, paging: this.paging }, this.type)
            .then((res: IndexReportRepVO) => {
                if (res && res.list) {
                    res.list.forEach(element => {
                        if (element.adjustProgerss && element.adjustProgerss.length) {
                            element.adjustProgerss = element.adjustProgerss.split(',');
                            let adjustProgerssName = [];
                            element.adjustProgerss.forEach(e => {
                                adjustProgerssName.push(this.adjustProgresssPojo[e]);
                            });
                            element.adjustProgerssName = adjustProgerssName;
                        } else {
                            element.adjustProgerss = [];
                            element.adjustProgerssName = [];
                        }
                    });
                }
                this.tableData = res?.list || [];
                this.paging.total = res?.total || 0;
                this.tableLoading = false;
            })
            .finally(() => {
                this.tableLoading = false;
            });
    }

    /**
     * 按钮点击事件
     */
    handleBtn(type: string): void {
        if (type == 'search') {
            this.paging.currentPage = 1;
            this.getTableData();
        } else if (type == 'refresh') {
            this.getTableData();
        } else if (type == 'layout') {
            this.layoutDialog = true;
        } else if (type == 'export') {
            const checkedKeys = (this.$refs['risk-table'] as any).checkRowKeys;
            const url = this.type === 'today' ? '/event/report/export' : '/event/history/report/export';
            downLoadFile({
                url,
                method: 'post',
                data: checkedKeys.length ? { resultIds: checkedKeys } : this.searchParams,
            });
            this.$nextTick(() => {
                (this.$refs['risk-table'] as any).resetCheckRowKeys();
            });
        }
    }

    /**
     * 动态设置单元格样式
     */
    cellStyle({ row, column }) {
        if (column.property === 'adjustProgerss') {
            if (!row.adjustProgerss || !row.adjustProgerss.length) {
                return;
            }
            if (row.adjustProgerss.includes('5')) {
                return {
                    backgroundColor: 'red',
                };
            } else if (row.adjustProgerss.includes('1') || row.adjustProgerss.includes('2') || row.adjustProgerss.includes('3')) {
                return {
                    // 黄色
                    backgroundColor: '#fefe1f',
                };
            } else if (row.adjustProgerss.includes('4')) {
                return {
                    backgroundColor: 'white',
                };
            }
        }
    }

    /**
     * 连续超限天数 tag样式设置
     */
    handleTagStyle(value): string {
        if (value <= 5) {
            return 'tag1';
        } else if (value < 10 && value > 5) {
            return 'tag2';
        } else if (value >= 10) {
            return 'tag3';
        } else {
            return 'tag-d';
        }
    }

    handleBtnLook(obj: any): void {
        this.resultId = obj.resultId;
        this.history = obj.eventStatus === '2';
        this.staticVisible = true;
        // const msg = {
        //     type: 'static-detail',
        //     path: `/lookStaticDetail?resultId=${obj.resultId}&history=${this.type === 'history'}`,
        //     title: `静态报告详情-${obj.resultId}`,
        // };
        // top.window.postMessage(msg, '*');
        // this.$emit('handelOperate', { record: obj, history: this.type === 'history', clickRecord: obj });
    }

    // 格式化产品代码
    private formatDictFundCodes(cellValue): string {
        let valueStr = XEUtils.map(cellValue, item => {
            if (item) {
                return item.dictKey + '(' + item.dictKeyName + ')';
            } else {
                return '--';
            }
        });
        return valueStr.toString();
    }
}
</script>
<style lang="scss" scoped>
.content {
    height: 100%;
    .search-bar {
        padding-top: 10px;
    }
    .flex {
        display: flex;
    }
    .flex8 {
        flex: 8;
    }
    .flex9 {
        flex: 9;
    }
    .flex11 {
        flex: 11;
    }

    .flex13 {
        flex: 13;
        margin: 5px 0 5px 5px;
        text-align: center;
        overflow: hidden;
        white-space: nowrap;
    }
    .el-form-item {
        margin-bottom: 10px !important;
    }

    .form {
        display: grid;
        grid-template-columns: 1fr 1fr 4fr;
        border: 1px solid #ccc;
        padding: 8px;
        margin-bottom: 10px;
        .el-form-item {
            margin-bottom: 0px !important;
        }
        .item {
            width: 60%;
        }
    }
    /deep/ .el-select__tags {
        flex-wrap: nowrap;
    }
    /deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light {
        display: flex;
        align-items: center;
        width: 62%;
        max-width: fit-content;
        padding: 0px 5px 0 0;
        margin: 4px 0px 2px 2px;
        .el-select__tags-text {
            display: inline-block;
            font-size: 12px;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }

    .tag1,
    .tag2,
    .tag3,
    .tag-d {
        color: #fff;
        width: 35px;
        text-align: center;
    }
    .tag1 {
        background-color: #e9d571;
        border-color: #e9d571;
    }
    .tag2 {
        background-color: #e98730;
        border-color: #e98730;
    }
    .tag3 {
        background-color: red;
        border-color: red;
    }

    a {
        color: #578bec;
        padding: 0 5px;
    }
}

/***  collapse-tags样式 ***/
/deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light {
    display: flex;
    align-items: center;
    width: 100%;
    max-width: fit-content;
    padding: 0px 5px 0 0;
    margin: 4px 0px 2px 2px;
    .el-select__tags-text {
        display: inline-block;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}
/deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light:first-of-type {
    width: 63%;
}
/deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light:last-of-type {
    // width: calc(85% - 15px);
    width: 85%;
}
// /deep/ .el-select__tags .el-select__input {
//     margin-left: 0;
// }
/***  collapse-tags样式 ***/
</style>
